package pswvclass.pswvandroid2.com.risk;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.kwords.KwordList;
import pswvclass.pswvandroid2.com.po.Risk;
import pswvclass.pswvandroid2.com.util.DBHelper;
import pswvclass.pswvandroid2.com.util.HttpUtils;

/**
 * Created by Administrator on 2018/11/1.
 */
public class RiskAdd extends Fragment implements View.OnClickListener {
    private String tag = "RiskAdd";
    private TextView risk_kword;
    private TextView risk_context;
    private Button add_risk;
    protected static final int SUCCESS = 0;
    protected static final int ERROR = 1;
    protected static final int SUCCESS_SHARE_YES = 2;
    protected static final int SUCCESS_SHARE_YES1 = 4;
    protected static final int SUCCESS_SHARE_NO = 3;
    protected static final int SUCCESS_SHARE_NO1 = 5;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.pswv_risk_add, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        risk_kword = (EditText) getView().findViewById(R.id.risk_kword);
        risk_context = (EditText) getView().findViewById(R.id.risk_context);
        add_risk = (Button) getView().findViewById(R.id.add_risk);
        try {
            add_risk.setOnClickListener(this);
        } catch (Exception e) {

            e.printStackTrace();
            Log.v(tag, e + "");
        }

    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SUCCESS: {
                    final String kword1 = risk_kword.getText().toString().trim();
                    final String context1 = risk_context.getText().toString().trim();
                    if (TextUtils.isEmpty(kword1) || TextUtils.isEmpty(context1)) {
                        Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    DBHelper db = new DBHelper(getContext());
                    SQLiteDatabase sd = db.getWritableDatabase();
                    int userId = 0;
                    Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                    while (cursor.moveToNext()) {
                        userId = cursor.getInt(0);
                    }
                    cursor.close();
                    final int finalUserId = userId;
                    new Thread() {
                        public void run() {
                            try {
                                HttpUtils hu = new HttpUtils();
                                String data2;
                                final String src = getResources().getString(R.string.src_mysql) + "pswv/api/riskAction/addRisk";
                                final Map<String, String> map1 = new HashMap<String, String>();
                                map1.put("userId", finalUserId + "");
                                map1.put("kWord", kword1);
                                map1.put("content", context1);
                                data2 = hu.submitPostData(src, map1, "utf-8");
                                JSONObject jsonObj = new JSONObject(data2);
                                int result = Integer.parseInt(jsonObj.getString("code"));
                                if (result == 0) {
                                    Message msg = Message.obtain();
                                    msg.what = SUCCESS_SHARE_YES;
                                    mHandler.sendMessage(msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Message msg = Message.obtain();
                                msg.what = ERROR;
                                mHandler.sendMessage(msg);
                                Log.v(tag, e + "");
                            }
                        }
                    }.start();
                }
                break;
                case SUCCESS_SHARE_NO: {
                    final String kword2 = risk_kword.getText().toString().trim();
                    final String context2 = risk_context.getText().toString().trim();
                    if (TextUtils.isEmpty(kword2) || TextUtils.isEmpty(context2)) {
                        Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    new Thread() {
                        public void run() {
                            try {
                                HttpUtils hu = new HttpUtils();
                                String data2;
                                final String src = getResources().getString(R.string.src_mysql) + "pswv/api/riskAction/addRisk";
                                final Map<String, String> map1 = new HashMap<String, String>();
                                map1.put("kWord", kword2);
                                map1.put("content", context2);
                                data2 = hu.submitPostData(src, map1, "utf-8");
                                JSONObject jsonObj = new JSONObject(data2);
                                int result = Integer.parseInt(jsonObj.getString("code"));
                                if (result == 0) {
                                    Message msg = Message.obtain();
                                    msg.what = SUCCESS_SHARE_NO1;
                                    mHandler.sendMessage(msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Message msg = Message.obtain();
                                msg.what = ERROR;
                                mHandler.sendMessage(msg);
                                Log.v(tag, e + "");
                            }
                        }
                    }.start();
                }
                break;
                case SUCCESS_SHARE_YES: {
                    final String kword3 = risk_kword.getText().toString().trim();
                    final String context3 = risk_context.getText().toString().trim();

                    if (TextUtils.isEmpty(kword3) || TextUtils.isEmpty(context3)) {
                        Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    new Thread() {
                        public void run() {
                            try {
                                HttpUtils hu = new HttpUtils();
                                String data2;
                                final String src = getResources().getString(R.string.src_mysql) + "pswv/api/riskAction/addRisk";
                                final Map<String, String> map1 = new HashMap<String, String>();
                                map1.put("kwords", kword3);
                                map1.put("content", context3);
                                data2 = hu.submitPostData(src, map1, "utf-8");
                                JSONObject jsonObj = new JSONObject(data2);
                                int result = Integer.parseInt(jsonObj.getString("code"));
                                if (result == 0) {
                                    Message msg = Message.obtain();
                                    msg.what = SUCCESS_SHARE_YES1;
                                    mHandler.sendMessage(msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Message msg = Message.obtain();
                                msg.what = ERROR;
                                mHandler.sendMessage(msg);
                                Log.v(tag, e + "");
                            }
                        }
                    }.start();
                }
                break;
                case SUCCESS_SHARE_YES1: {
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, new RiskAdd()).commit();
                    Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
                }
                break;
                case SUCCESS_SHARE_NO1: {
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, new RiskAdd()).commit();
                    Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
                }
                break;
                case ERROR: {
                    Toast.makeText(getContext(), "连接错误 ....", Toast.LENGTH_SHORT).show();
                }
                break;
                default:
                    break;
            }

        }

        ;

    };


    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.add_risk:
                AlertDialog.Builder bb = new AlertDialog.Builder(getContext());
                bb.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int b) {
                        Message msg = Message.obtain();
                        msg.what = SUCCESS;
                        mHandler.sendMessage(msg);
                    }
                });
                bb.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Message msg = Message.obtain();
                        msg.what = SUCCESS_SHARE_NO;
                        mHandler.sendMessage(msg);
                    }
                });
                bb.setMessage("是否共享？");
                bb.setTitle("提示");
                bb.show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, new RiskList()).commit();
                    return true;
                }
                return false;
            }
        });
    }
}
